<template>
    <a-spin :spinning="confirmLoading">
        <j-form-container :disabled="formDisabled">
            <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
                <a-row>
                    <a-col :span="24">
                        <a-form-model-item label="房间号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="roomCode">
                            <a-select v-model="model.roomCode" placeholder="请选择房间号" @change="handleRoomCodeChange">
                                <a-select-option v-for="item in dataSource" :key="item.roomCode" :value="item.roomCode">
                                    {{ item.roomCode }}
                                    （
                                    {{ item.roomLevelCode_dictText }} {{ item.roomTypeCode_dictText }}
                                    ）
                                </a-select-option>
                            </a-select>
                        </a-form-model-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-model-item label="维修时段" :labelCol="labelCol" :wrapperCol="wrapperCol"
                            prop="beginAndEndTime">
                            <a-range-picker :disabled-date="disabledDate" v-model="model.beginAndEndTime"
                                style="width: 100%;" @change="onBeginAndEndTimeChange" format="YYYY-MM-DD">
                                <template slot="dateRender" slot-scope="current">
                                    <div class="ant-calendar-date" :style="getCurrentStyle(current)">
                                        {{ current.date() }}
                                    </div>
                                </template>
                            </a-range-picker>
                        </a-form-model-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-model-item label="维修原因" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="repairReason">
                            <a-input v-model="model.repairReason" placeholder="请输入维修原因"></a-input>
                        </a-form-model-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-model-item label="已完成" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="repairStatus">
                            <!-- <a-input v-model="model.repairStatus" placeholder="请输入状态"></a-input> -->
                            <j-switch v-model="model.repairStatus" :options="['20', '00']"></j-switch>
                        </a-form-model-item>
                    </a-col>
                </a-row>
            </a-form-model>
        </j-form-container>
    </a-spin>
</template>

<script>

import { httpAction, getAction, postAction } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import dayjs from 'dayjs'

export default {
    name: 'RoomRepairForm',
    components: {
    },
    mixins: [JeecgListMixin],
    props: {
        //表单禁用
        disabled: {
            type: Boolean,
            default: false,
            required: false
        }
    },
    data() {
        let validateBeginAndEndTime = (rule, value, callback) => {
            if (!value || value.length === 0) {
                callback(new Error('请完善内容'));
            } else {
                const dateList = []
                this.unableDateList.forEach(item => {
                    dateList.push(...item.dateList)
                })
                const tempDay = []
                const startDay = dayjs(this.model.beginTime)
                const endDay = dayjs(this.model.endTime)
                const diffDay = dayjs(endDay).diff(dayjs(startDay), 'day')
                for (let d = 0; d <= diffDay; d++) {
                    tempDay.push(dayjs(startDay).add(d, 'day').format('YYYY-MM-DD'))
                }
                for (let item of dateList) {
                    if (tempDay.indexOf(item) !== -1) {
                        callback(new Error('所选时间段不能包含已占用时间'));
                    }
                }
                callback();
            }
        }
        return {
            dayjs,
            model: {
                beginAndEndTime: []
            },
            labelCol: {
                xs: { span: 24 },
                sm: { span: 5 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 },
            },
            confirmLoading: false,
            validatorRules: {
                roomCode: [{ required: true, message: '请完善内容' }],
                beginAndEndTime: [{ required: true, validator: validateBeginAndEndTime, trigger: 'change' }],
                repairStatus: [{ required: true, message: '请完善内容' }],
            },
            url: {
                list: '/room/roomStatus/list',
                add: "/room/roomRepairPlan/add",
                edit: "/room/roomRepairPlan/edit",
                queryById: "/room/roomRepairPlan/queryById",
                canRepair: "/room/roomRepairPlan/queryUnableDate",
            },
            columns: [],
            isorter: {
                column: 'roomCode',
                order: 'asc',
            },
            ipagination: {
                current: 1,
                pageSize: 9999,
            },
            unableDateList: []
        }
    },
    computed: {
        formDisabled() {
            return this.disabled
        },
    },
    created() {
        //备份model原始值
        this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
        disabledDate(current) {
            // Can not select days before today and today
            const dateList = []
            this.unableDateList.forEach(item => {
                dateList.push(...item.dateList)
            })
            if (dateList.includes(dayjs(current).format('YYYY-MM-DD'))) {
                return true;
            }
            return current && current < dayjs().subtract(1, 'day').endOf('day')
        },
        handleRoomCodeChange(roomCode) {
            this.unableDateList = []
            this.model.beginAndEndTime = []
            this.getCanRepair(roomCode)
        },
        getCanRepair(roomCode) {
            getAction(this.url.canRepair, { roomCode: roomCode }).then(res => {
                if (res.success) {
                    let resResult = []
                    if (this.model.beginTime !== '' && this.model.endTime !== '') {
                        resResult = res.result.filter(item => {
                            return item.startDate !== this.model.beginTime && item.endDate !== this.model.endTime
                        })
                    }
                    resResult.forEach(item => {
                        const dateDiff = dayjs(item.endDate).diff(dayjs(item.startDate), 'day')
                        const temp = []
                        for (let i = 0; i <= dateDiff; i++) {
                            temp.push(dayjs(item.startDate).add(i, 'day').format('YYYY-MM-DD'))
                        }
                        this.unableDateList.push({
                            status: item.status,
                            dateList: temp

                        })
                    })
                } else {
                    this.$message.error(res.message)
                }
            })
        },
        getCurrentStyle(current, today) {
            const currentDate = dayjs(current).format('YYYY-MM-DD')
            const style = {};
            const st = localStorage.getItem('roomStateBackgroundColor')
            let csf
            if (st) {
                csf = JSON.parse(st)
            } else {
                csf = Object.assign({}, this.defaultColor)
            }
            for (let ud of this.unableDateList) {
                if (ud.dateList.includes(currentDate)) {
                    if (ud.status === 'VD' || ud.status === 'OD') {
                        // style.border = '1px solid black'
                        // style.borderRadius = '50%';
                        style.background =
                            'repeating-linear-gradient(150deg, '
                            + checkBackgroundColor.background + ' 2px, '
                            + checkBackgroundColor.background + ' 1px, '
                            + checkBackgroundColor.background + ' 10px, black 11px)'
                        // 'repeating-linear-gradient(150deg, #e65926 2px, #e65926 1px, #e65926 10px, black 11px)'
                    } else {
                        // style.border = '1px solid black'
                        // style.borderRadius = '50%';
                        style.background = csf[ud.status]

                    }
                    return style
                }
            }
            return style;
        },
        onBeginAndEndTimeChange(value, dateString) {
            this.model.beginTime = dateString[0]
            this.model.endTime = dateString[1]
        },
        add() {
            this.edit(this.modelDefault);
        },
        edit(record) {
            if (record.beginTime !== '' && record.endTime !== '') {
                this.model = Object.assign({}, record)
                this.model.beginAndEndTime = [
                    record.beginTime,
                    record.endTime
                ]
            } else {
                this.model = Object.assign({}, record)
            }
            if (record.roomCode) {
                this.getCanRepair(record.roomCode)
            }
            this.visible = true;
        },
        submitForm() {
            const that = this;
            // 触发表单验证
            this.$refs.form.validate(valid => {
                if (valid) {
                    that.confirmLoading = true;
                    let httpurl = '';
                    let method = '';
                    if (!this.model.id) {
                        httpurl += this.url.add;
                        method = 'post';
                    } else {
                        httpurl += this.url.edit;
                        method = 'put';
                    }
                    httpAction(httpurl, this.model, method).then((res) => {
                        if (res.success) {
                            that.$message.success(res.message);
                            that.$emit('ok');
                        } else {
                            that.$message.warning(res.message);
                        }
                    }).finally(() => {
                        that.confirmLoading = false;
                    })
                }

            })
        },
    }
}
</script>